
using System;
using System.Data;
using System.Linq;
using System.Linq.Dynamic;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;

using Abp.UI;
using Abp.AutoMapper;
using Abp.Extensions;
using Abp.Authorization;
using Abp.Domain.Repositories;
using Abp.Application.Services.Dto;
using Abp.Linq.Extensions;
using JYJ.AiYard.Database;
using JYJ.AiYard.StationManagement.TbYardPayNormals;
using JYJ.AiYard.StationManagement.TbYardPayNormals.Dtos;
using JYJ.AiYard.StationManagement.TbYardPayNormals.DomainService;
using JYJ.AiYard.StationManagement.TbYardPayNormals.Authorization;
using JYJ.AiYard.StationManagement.YardReport;
using JYJ.AiYard.StationManagement.YardCommonHald;

namespace JYJ.AiYard.StationManagement.TbYardPayNormals
{
    /// <summary>
    /// TbYardPayNormal应用层服务的接口实现方法  
    ///</summary>
    [AbpAuthorize]
    public class TbYardPayNormalAppService : AiYardAppServiceBase, ITbYardPayNormalAppService
    {
        private readonly IRepository<TbYardPayNormal, long> _entityRepository;

        private readonly IRepository<JYJ.AiYard.StationManagement.TbObjects.TbObjects, long> _entityTbObjectRepository;

        private readonly ITbYardPayNormalManager _entityManager;

        private readonly IAiYardDbTable _aiYardDbTable;
       // private readonly IAiYardDbTbYardPayNormalCol _aiYardDbTable;

        /// <summary>
        /// 构造函数 
        ///</summary>
        public TbYardPayNormalAppService(
        IRepository<TbYardPayNormal, long> entityRepository,
       IRepository<JYJ.AiYard.StationManagement.TbObjects.TbObjects, long> entityTbObjectRepository
        , IAiYardDbTable aiYardDbTable
        , ITbYardPayNormalManager entityManager
        )
        {
            _entityRepository = entityRepository;
            _entityTbObjectRepository = entityTbObjectRepository;
             _entityManager=entityManager;
             _aiYardDbTable = aiYardDbTable;
        }

         

        /// <summary>
        /// 获取TbYardPayNormal的分页列表信息
        ///</summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize(TbYardPayNormalPermissions.Query)]
        public async Task<PagedResultDto<TbYardPayNormalCol>> GetPaged2(GetTbYardPayNormalsInput input)
        {

            List<long> StationList = new List<long>();
            tbQFilterText filterText = input.FilterText.ToObject<tbQFilterText>();
            if (filterText.StationId == null || filterText.StationId <= 0)
            {
                StationList = GetCurrenUserOrganizationAndChildrenUnit();
            }
            else
            {
                StationList.Add((long)filterText.StationId);
            }
            var query = await  _aiYardDbTable.QueryTbYardPayNormalList(StationList);
            var query1 = query.AsQueryable();
           
            var count = query1.Count();

            var entityList = query1
                .OrderBy(input.Sorting).AsNoTracking()
                .PageBy(input)
                .ToList();

            return new PagedResultDto<TbYardPayNormalCol>(count, entityList);
        }

        /// <summary>
        /// 获取TbYardPayNormal的分页列表信息
        ///</summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize(TbYardPayNormalPermissions.Query)]
        public async Task<PagedResultDto<TbYardPayNormalListDto>> GetPaged(GetTbYardPayNormalsInput input)
        {

            var query = _entityRepository.GetAll();
            // TODO:根据传入的参数添加过滤条件


            var count = await query.CountAsync();

            var entityList = await query
                      .Where(o => GetCurrenUserOrganizationAndChildrenUnit().Contains(o.Station_ID))
                          .OrderBy(input.Sorting).AsNoTracking()
                    .PageBy(input)
                    .ToListAsync();
             
            var entityListDtos = entityList.MapTo<List<TbYardPayNormalListDto>>();

            return new PagedResultDto<TbYardPayNormalListDto>(count, entityListDtos);
        }


        /// <summary>
        /// 通过指定id获取TbYardPayNormalListDto信息
        /// </summary>
        [AbpAuthorize(TbYardPayNormalPermissions.Query)] 
		public async Task<TbYardPayNormalListDto> GetById(EntityDto<long> input)
		{
			var entity = await _entityRepository.GetAsync(input.Id);

		    return entity.MapTo<TbYardPayNormalListDto>();
		}

		/// <summary>
		/// 获取编辑 TbYardPayNormal
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		[AbpAuthorize(TbYardPayNormalPermissions.Create,TbYardPayNormalPermissions.Edit)]
		public async Task<GetTbYardPayNormalForEditOutput> GetForEdit(NullableIdDto<long> input)
		{
			var output = new GetTbYardPayNormalForEditOutput();
            TbYardPayNormalEditDto editDto;
            List<CHours> ch=new List<CHours>();

			if (input.Id.HasValue)
			{
				var entity = await _entityRepository.GetAsync(input.Id.Value);

				editDto = entity.MapTo<TbYardPayNormalEditDto>();

                var CurrEntity = await _entityRepository.GetAll()
                    .Where(o => o.Station_ID == entity.Station_ID && o.CardTypeID == entity.CardTypeID)
                    .ToListAsync();
                if (CurrEntity.Count > 0)
                {
                    foreach (var tn in CurrEntity)
                    {
                        CHours c = new CHours();
                        c.id = tn.CHour;
                        c.CHoursValue = tn.Amount;
                        ch.Add(c);
                    }
                   
                } 
            }
			else
			{
                //新建
				editDto = new TbYardPayNormalEditDto();
                for (int i = 1; i <= 24; i++)
                {
                    CHours c = new CHours();
                    c.id = i;
                    ch.Add(c);
                }
			}

			output.TbYardPayNormal = editDto;
            output.CHourValue = ch;
			return output;
		}


		/// <summary>
		/// 添加或者修改TbYardPayNormal的公共方法
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		[AbpAuthorize(TbYardPayNormalPermissions.Create,TbYardPayNormalPermissions.Edit)]
		public async Task CreateOrUpdate(CreateOrUpdateTbYardPayNormalInput input)
		{
            if (input.TbYardPayNormal.Station_ID <= 0)
            {
                throw new UserFriendlyException("请选择确定的场所名称");
            }
            if (input.TbYardPayNormal.Id.HasValue)
			{
				await Update(input.TbYardPayNormal,input.CHourValue);
			}
			else
			{
				await Create(input.TbYardPayNormal, input.CHourValue);
			}
		}


		/// <summary>
		/// 新增TbYardPayNormal
		/// </summary>
		[AbpAuthorize(TbYardPayNormalPermissions.Create)]
		protected virtual async Task Create(TbYardPayNormalEditDto input,List<CHours> CHourValues)
		{
            //查看此卡类型是否已经添加，已经添加则不添加
            if (_entityRepository.GetAll().Where(o => o.Station_ID == input.Station_ID && o.CardTypeID == input.CardTypeID).ToList().Count > 0)
            {
                throw new UserFriendlyException("已经添加此卡类信息！");
            }
            else
            {
                var cardType = await _entityTbObjectRepository.GetAll().Where(o => o.Station_ID == input.Station_ID && o.OBJ_ID == input.CardTypeID).ToListAsync();
                if (cardType.Count > 0)
                    input.CardType = cardType[0].OBJ_Name;
                else
                    throw new UserFriendlyException("所选择的类型未设置或未选择！");

          
                foreach (CHours c in CHourValues)
                {
                    var entity = input.MapTo<TbYardPayNormal>();
                    entity.CHour = c.id;
                    entity.Amount = c.CHoursValue;

                    entity = await _entityRepository.InsertAsync(entity);
                }                
            }
		}

		/// <summary>
		/// 编辑TbYardPayNormal
		/// </summary>
		[AbpAuthorize(TbYardPayNormalPermissions.Edit)]
		protected virtual async Task Update(TbYardPayNormalEditDto input, List<CHours> CHourValues)
		{
            //获取ObjectName
            var cardType = await _entityTbObjectRepository.GetAll().Where(o => o.Station_ID == input.Station_ID &&  o.OBJ_ID == input.CardTypeID).ToListAsync();
            if (cardType.Count > 0)
                input.CardType = cardType[0].OBJ_Name;
            else
                throw new UserFriendlyException("所选择的类型未设置或未选择！");
            

            foreach (CHours c in CHourValues)
            { 
                var entity = await _entityRepository.GetAll().Where(o => o.Station_ID == input.Station_ID && o.CardTypeID == input.CardTypeID && o.CHour == c.id).FirstAsync();
                entity.Free_Forever = input.Free_Forever;
                entity.Free_Minute = input.Free_Minute;
                entity.HighPay = input.HighPay;
                entity.HHourPay = input.HHourPay;
                entity.OverTime = input.OverTime;

                entity.CHour = c.id;
                entity.Amount = c.CHoursValue;

                await _entityRepository.UpdateAsync(entity);
            } 
		}



		/// <summary>
		/// 删除TbYardPayNormal信息的方法
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		[AbpAuthorize(TbYardPayNormalPermissions.Delete)]
		public async Task Delete(EntityDto<long> input)
		{
			//TODO:删除前的逻辑判断，是否允许删除 
            var entity = _entityRepository.GetAll().Where(o => o.Id == input.Id).FirstOrDefault();

            var delentity = _entityRepository.GetAll()
                .Where(o => o.Station_ID == entity.Station_ID && o.CardTypeID == entity.CardTypeID).ToList();


            List<long> dl = new List<long>();
            foreach (var tb in delentity)
            {
                dl.Add(tb.Id);
            }
            _entityRepository.DeleteAsync(s => dl.Contains(s.Id)); 
        }



		/// <summary>
		/// 批量删除TbYardPayNormal的方法
		/// </summary>
		[AbpAuthorize(TbYardPayNormalPermissions.BatchDelete)]
		public async Task BatchDelete(List<long> input)
		{
            // TODO:批量删除前的逻辑判断，是否允许删除 
            foreach (var dg in input)
            {
                var entity = _entityRepository.GetAll().Where(o => o.Id == dg).FirstOrDefault();

                var delentity = _entityRepository.GetAll()
                    .Where(o => o.Station_ID == entity.Station_ID && o.CardTypeID == entity.CardTypeID).ToList();
                List<long> dl = new List<long>();
                foreach (var tb in delentity)
                {
                    dl.Add(tb.Id);
                }
                _entityRepository.DeleteAsync(s => dl.Contains(s.Id));
            }
        }


		///// <summary>
		///// 导出TbYardPayNormal为excel表,等待开发。
		///// </summary>
		///// <returns></returns>
		//public async Task<FileDto> GetToExcel()
		//{
		//	var users = await UserManager.Users.ToListAsync();
		//	var userListDtos = ObjectMapper.Map<List<UserListDto>>(users);
		//	await FillRoleNames(userListDtos);
		//	return _userListExcelExporter.ExportToFile(userListDtos);
		//}

    }
}


